<template>
    <div class="wh100p zi9 bgc-f2 fysxc">
        <van-cell-group class="w100p my20">
            <van-field v-model="title" label="标题" placeholder="请输入标题" />
            <van-field v-model="des" label="描述" placeholder="请输入描述" />
            <van-field v-model="price" label="价格" placeholder="请输入价格" />
        </van-cell-group>
        <div class="w344">
            <van-uploader :after-read="afterRead">
                <img :src="img" v-if="img" width="80" height="80" class="bgc-f" />
            </van-uploader>
        </div>
        <van-button type="info" class="w200 mt40-b10" @click="submitData">{{buttontext}}</van-button>
        <van-button type="info" class="w200" @click="noset">取消</van-button>
    </div>
</template>

<script>
export default {
    props: {
        newdata: { type: Object, default: () => {} },
        buttontext: { type: String, default: "" },
    },
    data() {
        return {
            title: "",
            des: "",
            price: "",
            img: "",
            itemId: "",
            file: null,
        };
    },
    methods: {
        afterRead(file) {
            this.img = file.content;
            const formData = new FormData();
            formData.append("file", file.file);
            this.file = formData;
        },
        noset() {
            this.$emit("noset");
        },
        submitData() {
            const { title, des, price, img } = this;
            if (this.buttontext == "增加") {
                this.$store.dispatch("addGoodsServer", {
                    title: this.newdata.title,
                    index: this.newdata.index,
                    file: this.file,
                    data: { title, des, price, img: img },
                });
            } else if (this.buttontext == "修改") {
                const uploadData = {
                    id: this.itemId
                } 
                const item = {
                    title: this.newdata.title,
                    index: this.newdata.index,
                }
                for (const key in this.newdata.item) {
                    if(this.newdata.item[key] != this[key] && this[key]){
                        if (key == 'img') {
                            uploadData[key] = this.file
                        }else{
                            uploadData[key] = this[key]
                        } 
                    }
                }
                this.$store.dispatch('setGoodsServer',{item, uploadData})
            }

            this.noset();
        },
    },
    created() {
        const itemData = this.newdata.item;
        this.title = itemData ? itemData.title : "";
        this.des = itemData ? itemData.des : "";
        this.price = itemData ? itemData.price : "";
        this.img = itemData ? itemData.img : "";
        this.itemId = itemData ? itemData._id : "";
    },
};
</script>

<style>
</style>